#region File Description
//-----------------------------------------------------------------------------
// WanderBehavior.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Dude_Platformer
{
    public class WanderBehavior : Behavior
    {
        public WanderBehavior(Enemy entity)
            : base(entity)
        {
        }

        /// <summary>
        /// Update will make modify the associated entity's orientation and speed in
        /// to make him wander around. The logic contained in this function is the same
        /// as we saw in the Chase and Evade sample.
        /// </summary>
        public override void Update(GameTime gameTime)
        {
            Entity.isShooting = false;
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // Calculate tile position based on the side we are walking towards.
            float posX = Entity.Position.X + Entity.LocalBounds.Width / 2 * (int)Entity.Direction;
            int tileX = (int)Math.Floor(posX / Tile.Width) - (int)Entity.Direction;
            int tileY = (int)Math.Floor(Entity.Position.Y / Tile.Height);

            if (Entity.waitTime > 0)
            {
                // Wait for some amount of time.
                Entity.waitTime = Math.Max(0.0f, Entity.waitTime - (float)gameTime.ElapsedGameTime.TotalSeconds);
                if (Entity.waitTime <= 0.0f)
                {
                    // Then turn around.
                    Entity.Direction = (FaceDirection)(-(int)Entity.Direction);
                }
            }
            else
            {
                // If we are about to run into a wall or off a cliff, start waiting.
                if (Entity.Level.GetCollision(tileX + (int)Entity.Direction, tileY - 1) == TileCollision.Impassable ||
                    Entity.Level.GetCollision(tileX + (int)Entity.Direction, tileY) == TileCollision.Passable)
                {
                    Entity.waitTime = Enemy.MaxWaitTime;
                }
                else
                {
                    // Move in the current direction.
                    Vector2 velocity = new Vector2((int)Entity.Direction * Enemy.MoveSpeed * elapsed, 0.0f);
                    Entity.Position = Entity.Position + velocity;
                }
            }
        }
    }
}
